//app.js   
const websocket = require('/utils/websocket.js')

App({ 
  onShow:function(options){
    // 用户进入的名片id
    options.query.share_card_id && wx.setStorageSync('share_card_id', options.share_card_id)
    // 用户进入的分享人id
    options.query.share_user_id && wx.setStorageSync('share_user_id', options.share_user_id)
    // 二维码参数解析
    var str = decodeURIComponent(options.query.scene);
    var arr = str.split(',');
    var scene = [];
    for(var i=0;i<arr.length;i++){
      var s = arr[i].split(':');
      scene[s[0]] = s[1];
    }
    if(scene['cid']){
      wx.setStorageSync('share_card_id', scene['cid'])
    }
    if(scene['uid']){
      wx.setStorageSync('share_user_id', scene['uid'])
    }
  },
  onLaunch: function (options) {
    var that = this;
    that.siteInfo.is_first = 1;
    // 机型
    wx.getSystemInfo({
      success: function (res) {
        wx.setStorageSync('systemInfo', res)
      },
    })
    // 用户进入场景
    wx.setStorageSync('scene', options.scene)
    // 用户进入的名片id
    wx.setStorageSync('share_card_id', options.query.share_card_id || wx.getStorageSync('share_card_id'))
    // 用户进入的分享人id
    wx.setStorageSync('share_user_id', options.query.share_user_id || wx.getStorageSync('share_user_id'))
    // 二维码参数解析
    console.log(options)
    var str = decodeURIComponent(options.query.scene);
    var arr = str.split(',');
    var scene = [];
    for(var i=0;i<arr.length;i++){
      var s = arr[i].split(':');
      scene[s[0]] = s[1];
    }
    if(scene['cid']){
      wx.setStorageSync('share_card_id', scene['cid'])
    }
    if(scene['uid']){
      wx.setStorageSync('share_user_id', scene['uid'])
    }
    that.userBehavior(0,'进入小程序')

    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        console.log('onCheckForUpdate====', res)
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          console.log('res.hasUpdate====')
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                console.log('success====', res)
                // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            })
          })
        }
      })
    }
    // websocket
    //调通接口
    if(wx.getStorageSync('user_id')){
      websocket.connect(wx.getStorageSync('user_id'), function (res) {
        console.log('接收服务器发来的消息',res)
      })
    }
  },
  // 行为记录
  userBehavior:function (type, describe, stoptime, percent, id) {
    var that = this;
    var token = wx.getStorageSync("token") || 0;
    if(token){
      var params = {
        type, describe,
        stoptime: stoptime || 0, 
        percent: percent || 0, 
        id: id || 0
      }
      that.httpRequest('user/userBehavior',params,'get',false)
    }
    
  },
  // 请求
  httpRequest:function(url, params, method, check_login, _success, _fail, _complete){
    var that = this;
    var token = wx.getStorageSync("token") || 0;
    if(check_login && !token){
      wx.navigateTo({
        url: '/pages/welcome/welcome',
      })
      return;
    }
    params['token'] = token;
    params['user_id'] = wx.getStorageSync('user_id') || 0;
    params['enterprise_id'] = that.siteInfo.enterprise_id;
    params['card_id'] = wx.getStorageSync('share_card_id') ? wx.getStorageSync('share_card_id') : wx.getStorageSync('userInfo').card_id || 0;
    wx.request({
      url: that.siteInfo.siteroot + url,
      method: method,
      data: params,
      header: {
        "Content-type" : method == 'post' ? 'application/x-www-form-urlencode' : 'application/json',
      },
      success: function(res){
        if(res.data.code == 0){
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }else if(res.data.code == -1){
          wx.navigateTo({
            url: '/pages/welcome/welcome',
          })
          return;
        }else{
          _success && _success(res.data)
        }
      },
      fail: function(res){
        _fail && _fail(res.data)
      },
      complete: function(res){
        _complete && _complete(res.data)
      }
    })
  },
  globalData: {
    userInfo: null
  },
  siteInfo: require("siteinfo.js")
})